import { defineStore } from 'pinia';
import {
  getRegionTreeList,
  getEnumsList,
  getGearList,
  getManufacturerList,
} from '@/api/basedata';
import { getAcupointTree } from '@/api/formwork';
import { deptGetSelectList, getMenuList } from '@/api/account';

import { getSelectList } from '@/api/clinic/index';
import { getStorageSelectList } from '@/api/medical';
import type { RegionItem } from '@/types/region';
import { ca } from 'element-plus/es/locales.mjs';

export const useBaseDataStore = defineStore('baseData', {
  state: () => ({
    regions: [] as RegionItem[],
    enums: {} as Record<string, any>,
    isLoading: false,
    isRegionsLoaded: false,
    menuList: [] as any, // 用于菜单
    menuBtnList: [] as any, // 用于按钮权限
    directory: [] as any, // 用于目录组件的引用
    enumsSelect: [] as any, // 用于下拉选项
    deptSelectList: [] as any, // 用于科室下拉选项
    userSelectList: [] as any, // 用于用户下拉选项
    gearList: [] as any, // 充值档位
    mfrList: [] as any, // 厂家列表
    acupointTree: [] as any, // 穴位树
    Storage: [] as any, // 药库列表
    isEnumsLoaded: false,
    lastFetchTime: {
      regions: 0,
      enums: 0,
    },
  }),

  getters: {
    // 获取格式化的区域列表
    formattedRegions: (state) => {
      return state.regions.map((region: RegionItem) => ({
        label: region.name,
        value: region.code,
        ...region,
      }));
    },
    // 获取枚举选项
    getEnumOptions: (state) => {
      return (enumKey: string) => {
        const enumData = state.enums[enumKey];
        if (!enumData) return [];

        return Object.entries(enumData).map(([key, value]) => ({
          label: value,
          value: key,
        }));
      };
    },

    // 获取枚举值对应的标签
    getEnumLabel: (state) => {
      return (enumKey: string, value: string) => {
        const enumData = state.enums[enumKey];
        return enumData?.[value] || value;
      };
    },

    // 检查数据是否已加载
    isDataReady: (state) => {
      return state.isRegionsLoaded && state.isEnumsLoaded;
    },
  },

  actions: {
    // 获取药库
    async fetchStorageSelectList(forceRefresh = false) {
      // 如果已加载且不强制刷新，直接返回
      if (this.Storage &&this.Storage.length > 0 && !forceRefresh) {
        return this.Storage;
      }
      this.isLoading = true;
      try {
        const response = await getStorageSelectList();
        if (response?.code === '200') {
          this.Storage = response.data;
        }
      } catch (error) {
        //console.error('❌ 获取区域数据异常:', error);
        this.isRegionsLoaded = false;
        throw error;
      } finally {
        this.isLoading = false;
      }
    },
    // // 获取穴位数据
    // async fetchAcupointTree(forceRefresh = false) {
    //   // 如果已加载且不强制刷新，直接返回
    //   if (this.acupointTree.length > 0 && !forceRefresh) {
    //     return this.acupointTree;
    //   }
    //   this.isLoading = true;
    //   try {
    //     const response = await getAcupointTree();
    //     if (response?.code === '200') {
    //       this.acupointTree = response.data;
    //     }
    //   } catch (error) {
    //     //console.error('❌ 获取区域数据异常:', error);
    //     this.isRegionsLoaded = false;
    //     throw error;
    //   } finally {
    //     this.isLoading = false;
    //   }
    // },
    // 获取厂商数据
    async fetchManufacturerList(forceRefresh = false) {
      // 如果已加载且不强制刷新，直接返回
      if (this.mfrList && this.mfrList.length > 0 && !forceRefresh) {
        return this.mfrList;
      }
      this.isLoading = true;
      try {
        const response = await getManufacturerList();
        if (response?.code === '200') {
          this.mfrList = response.data.list;
        }
      } catch (error) {
        //console.error('❌ 获取区域数据异常:', error);
        this.isRegionsLoaded = false;
        throw error;
      } finally {
        this.isLoading = false;
      }
    },
    // 获取充值挡位
    async getGearList(forceRefresh = false) {
      // 如果已加载且不强制刷新，直接返回
      if (this.gearList && this.gearList.length > 0 && !forceRefresh) {
        return this.gearList;
      }
      this.isLoading = true;
      try {
        const response = await getGearList();
        if (response?.code === '200') {
          this.gearList = response.data;
        }
      } catch (error) {
        //console.error('❌ 获取区域数据异常:', error);
        this.isRegionsLoaded = false;
        throw error;
      } finally {
        this.isLoading = false;
      }
    },
    // 获取区域数据
    async fetchRegions(forceRefresh = false) {
      // 如果已加载且不强制刷新，直接返回
      if (this.isRegionsLoaded && !forceRefresh) {
        return this.regions;
      }
      this.isLoading = true;
      try {
        const response = await getRegionTreeList();
        this.regions = response.data;
        this.isRegionsLoaded = true;
        this.lastFetchTime.regions = Date.now();
        //console.log('✅ 获取区域数据成功:', this.regions.length, '条记录');
        return this.regions;
      } catch (error) {
        //console.error('❌ 获取区域数据异常:', error);
        this.isRegionsLoaded = false;
        throw error;
      } finally {
        this.isLoading = false;
      }
    },

    // 获取枚举数据
    async fetchEnums(forceRefresh = false) {
      // 如果已加载且不强制刷新，直接返回
      //console.log(this.isEnumsLoaded && !forceRefresh);

      if (this.isEnumsLoaded && !forceRefresh) {
        return this.enums;
      }
      this.isLoading = true;
      try {
        const response = await getEnumsList();
        //console.log(response.data, 'getEnumsList');

        if (response?.code == '200') {
          this.enums = response.data;
          this.isEnumsLoaded = true;
          this.lastFetchTime.enums = Date.now();
         
          return this.enums;
        } else {
          const errorMsg = response?.msg || '获取系统枚举和字典失败';
          //console.error('❌ 获取系统枚举和字典失败:', errorMsg);
          throw new Error(errorMsg);
        }
      } catch (error) {
        //console.error('❌ 获取系统枚举和字典异常:', error);
        this.isEnumsLoaded = false;
        throw error;
      } finally {
        this.isLoading = false;
      }
    },
    // 获取用户下拉选项
    async fetchUserSelectList(forceRefresh = false) {
      // 如果已加载且不强制刷新，直接返回
      this.isLoading = true;
      try {
        const response = await getSelectList();
        if (response?.code === '200') {
          this.userSelectList = response.data;
          
          return this.userSelectList;
        }
        const errorMsg = response?.msg || '获取用户下拉选项失败';
        //console.error('❌ 获取用户下拉选项失败:', errorMsg);
        throw new Error(errorMsg);
      } catch (error) {
        //console.error('❌ 获取用户下拉选项异常:', error);
        throw error;
      } finally {
        this.isLoading = false;
      }
    },

    //获取菜单
    async fetchMenuList(forceRefresh = false) {
      if (this.menuList && this.menuList.length > 0 && !forceRefresh) {
        return this.menuList;
      }
      this.isLoading = true;
      try {
        const response = await getMenuList();
        if (response?.code === '200') {
          this.menuList = response.data;
          //console.log('✅ 获取菜单成功:', this.menuList.length, '条记录');
          return this.menuList;
        }
      } catch (error) {
        throw error;
      }
    },
    // 获取权限下拉选项中按钮权限
    async findMenuType3Perms() {
      let result: any[] = [];
      // 递归遍历函数
      function traverse(nodes: any) {
        if (!Array.isArray(nodes)) return;

        for (const node of nodes) {
          // 检查当前节点的menuType是否为3
          if (node.menuType === '3' && node.perms) {
            result.push(node.perms);
          }

          // 如果有子节点，递归遍历
          if (node.children && node.children.length > 0) {
            traverse(node.children);
          }
        }
      }
      // 从data数组开始遍历
      if (this.menuList && Array.isArray(this.menuList)) {
        traverse(this.menuList);
      }
      this.menuBtnList = result;
      return result;
    },

    // 获取权限下拉选项中菜单权限
    async findMenuList(menuId: any) {
      let result: any = {};

      if (this.menuList && this.menuList.length === 0) {
        try {
          const response = await getMenuList();
          if (response?.code === '200') {
            this.menuList = response.data;
            if (this.menuList && Array.isArray(this.menuList)) {
              traverse(this.menuList);
            }
          }
        } catch (error) {
          throw error;
        }
      } else {
        if (this.menuList && Array.isArray(this.menuList)) {
          traverse(this.menuList);
        }
      }

      // 递归遍历函数
      function traverse(nodes: any) {
        if (!Array.isArray(nodes)) return;

        for (const node of nodes) {
          if (node.menuId == menuId) {
            result = node.children;
          }
          // 如果有子节点，递归遍历
          if (node.children && node.children.length > 0) {
            traverse(node.children);
          }
        }
      }

      return result;
    },

    // 获取科室下拉选项
    async fetchDeptSelectList(forceRefresh = false) {
      // 如果已加载且不强制刷新，直接返回

      this.isLoading = true;
      try {
        const response = await deptGetSelectList();
        if (response?.code === '200') {
          this.deptSelectList = response.data;
          
          return this.deptSelectList;
        }
        const errorMsg = response?.msg || '获取科室下拉选项失败';
        //console.error('❌ 获取科室下拉选项失败:', errorMsg);
        throw new Error(errorMsg);
      } catch (error) {
        //console.error('❌ 获取科室下拉选项异常:', error);
        throw error;
      } finally {
        this.isLoading = false;
      }
    },
    // 初始化所有数据
    async initializeData(forceRefresh = false) {
      try {
        await Promise.all([
          this.fetchMenuList(forceRefresh),
          this.fetchRegions(forceRefresh),
          this.fetchEnums(forceRefresh),
          this.fetchDeptSelectList(forceRefresh),
          this.fetchUserSelectList(forceRefresh),
          this.getGearList(forceRefresh),
          this.fetchManufacturerList(forceRefresh),
          // this.fetchAcupointTree(forceRefresh),
          this.fetchStorageSelectList(forceRefresh),
        ]);
        //console.log('✅ 区域和枚举数据初始化完成');
        return true;
      } catch (error) {
        //console.error('❌ 数据初始化失败:', error);
        return false;
      }
    },

    // 重置状态（使用 Pinia 内置 $reset 恢复到初始 state）
    resetState() {
      this.$reset();
    },

    // 检查数据是否需要刷新（可选的缓存策略）
    needsRefresh(type: 'regions' | 'enums', maxAge = 5 * 60 * 1000) {
      const lastFetch = this.lastFetchTime[type];
      return Date.now() - lastFetch > maxAge;
    },
    // 匹配枚举数据
    getEnumData(vlaue: string, name: string) {
      const keys = Object.keys(this.enums.enums);
      const enumData = keys.findIndex((key: string) => key === name);
      this.enumsSelect = enumData;
      if (enumData !== -1 && keys[enumData] !== undefined) {
        const enumList = this.enums.enums[keys[enumData]];
        if (Array.isArray(enumList)) {
          const find = enumList.find(
            (item: { value: string }) => item.value == vlaue
          );
          if (find) {
            return find.text;
          }
        }
      }
    },
    // FREQUENCY数据
    getFREQUENCYEnumData(vlaue: string, name: string) {
      const keys = Object.keys(this.enums.dicts);
      const enumData = keys.findIndex((key: string) => key === name);
      this.enumsSelect = enumData;
      if (enumData !== -1 && keys[enumData] !== undefined) {
        const enumList = this.enums.dicts[keys[enumData]];
        if (Array.isArray(enumList)) {
          const find = enumList.find(
            (item: { frequencyCode: string }) => item.frequencyCode === vlaue
          );
          if (find) {
            return find.frequencyName;
          }
        }
      }
    },
    // EXEC_TYPE
    getEXEC_TYPEEnumData(vlaue: string, name: string) {
      const keys = Object.keys(this.enums.dicts);
      const enumData = keys.findIndex((key: string) => key === name);
      this.enumsSelect = enumData;
      if (enumData !== -1 && keys[enumData] !== undefined) { 
        const enumList = this.enums.dicts[keys[enumData]];
        if (Array.isArray(enumList)) {
          const find = enumList.find(
            (item: { itemCode: string }) => item.itemCode === vlaue
          );
          if (find) {
            return find.itemName;
          }
        }
      }
    },
    // EXT_TYPE
    getEXT_TYPEEnumData(vlaue: string, name: string) {
      const keys = Object.keys(this.enums.dicts);
      const enumData = keys.findIndex((key: string) => key === name);
      this.enumsSelect = enumData;
      if (enumData !== -1 && keys[enumData] !== undefined) {
        const enumList = this.enums.dicts[keys[enumData]];
        if (Array.isArray(enumList)) {
          const find = enumList.find(
            (item: { itemCode: string }) => item.itemCode === vlaue
          );
          if (find) {
            return find.itemName;
          }
        }
      }
    },
    // UNIT
    getDictsData(vlaue: string, name: string) {
      const keys = Object.keys(this.enums.dicts);
      const enumData = keys.findIndex((key: string) => key === name);
      this.enumsSelect = enumData;
      if (enumData !== -1 && keys[enumData] !== undefined) {
        const enumList = this.enums.dicts[keys[enumData]];
        if (Array.isArray(enumList)) {
          const find = enumList.find(
            (item: { unitCode: string }) => item.unitCode === vlaue
          );
          if (find) {
            return find.unitText;
          }
        }
      }
    },
    // USAGE
    getDictsUSAGEData(vlaue: string, name: string) {
      const keys = Object.keys(this.enums.dicts);
      const enumData = keys.findIndex((key: string) => key === name);
      this.enumsSelect = enumData;
      if (enumData !== -1 && keys[enumData] !== undefined) {
        const enumList = this.enums.dicts[keys[enumData]];
        if (Array.isArray(enumList)) {
          const find = enumList.find(
            (item: { usageCode: string }) => item.usageCode === vlaue
          );
          if (find) {
            return find.usageName;
          }
        }
      }
    },
    // 获取枚举下拉选项
    getEnumSelect(name: string) {
      if (Object.keys(this.enums?.enums ?? {}).length === 0) {
        return [];
      }

      if (!this.enums.enums[name]) {
        return [];
      }

      if (this.enums.enums[name] && this.enums.enums[name].length > 0) {
        return this.enums.enums[name];
      } else {
        return [];
      }
    },
    // 获取枚举下拉选项
    getDictsSelect(name: string) {
      if (Object.keys(this.enums.dicts).length === 0) {
        return [];
      }

      if (this.enums.dicts[name] && this.enums.dicts[name].length > 0) {
        //console.log(this.enums.dicts[name]);

        return this.enums.dicts[name];
      } else {
        return [];
      }
    },
    // DOCTOR_ADVICE 枚举
    getDOCTORADVICEEnumData(name: string) {
      if (Object.keys(this.enums.dicts).length === 0) {
        return [];
      }

      if (this.enums.dicts[name] && this.enums.dicts[name].length > 0) {
        return this.enums.dicts[name];
      } else {
        return [];
      }
    },
    // 药品成分;氯化钠 字典接口中key=DRUG_INGR
    getDRUGINGREnumData(vlaue: string, name: string) {
      const keys = Object.keys(this.enums.dicts);
      const enumData = keys.findIndex((key: string) => key === name);
      this.enumsSelect = enumData;
      if (enumData !== -1 && keys[enumData] !== undefined) {
        const enumList = this.enums.dicts[keys[enumData]];
        if (Array.isArray(enumList)) {
          const find = enumList.find(
            (item: { itemCode: string }) => item.itemCode === vlaue
          );
          if (find) {
            return find.itemName;
          }
        }
      }
    },
    // 获取厂家匹配厂家name
    getMfrName(id: string) {
      if (this.mfrList.length === 0) {
        return '';
      }
      const find = this.mfrList.find(
        (item: { mfrId: string }) => item.mfrId === id
      );
      if (find) {
        return find.mfrName;
      } else {
        return '';
      }
    },
  },
});
